Backed Enum
code:plain
PHP Fatal error: Uncaught JsonException: Non-backed enums have no default serialization in /home/iigau/toy/php-enum/enum.php:65
Stack trace:
#0 /home/iigau/toy/php-enum/enum.php(65): json_encode() thrown in /home/iigau/toy/php-enum/enum.php on line 65
Enumを、JSONのようなフォーマットにシリアライズするには各々のcaseにスカラ値を紐づける必要がある。このスカラー値を持つcaseをBacked Caseという。 code:enum.php
<?php
declare(strict_types=1);
class Forecast
{
public Place $place;
public Wind $wind;
public Weather $weather;
function __construct(Place $place, Weather $weather, Wind $wind)
{
$this->place = $place;
$this->wind = $wind;
$this->weather = $weather;
}
}
class Place
{
public string $name;
public string $id;
function __construct($name, $id)
{
$this->name = "Tokyo";
$this->id = "12345678";
}
}
class Wind
{
public Direction $direction;
public int $strength;
function __construct(Direction $direction, int $strength)
{
$this->direction = $direction;
$this->strength = $strength;
}
}
enum Direction: int
{
case North = 0;
case Northwest = 1;
case West = 2;
case Southwest = 3;
case South = 4;
case Southeast = 5;
case East = 6;
case Northeast = 7;
}
enum Weather: int
{
case Sunny = 1;
case Rainy = 2;
case Cloudy = 3;
case Snowy = 4;
}
$forecast = new Forecast(new Place("Tokyo", "12345678"), Weather::Sunny, new Wind(Direction::Southeast, 1));
print_r($forecast);
$encoded = json_encode($forecast, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
echo $encoded, "\n";
このようにすることで、正しくJSON形式にシリアライズすることができる。
code:json
{
"place": {
"name": "Tokyo",
"id": "12345678"
},
"wind": {
"direction": 5,
"strength": 1
},
"weather": 1
}